package com.zyplayer.data.screen.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyplayer.data.screen.framework.db.bean.DatabaseRegistrationBean;
import com.zyplayer.data.screen.framework.json.DataResponse;
import com.zyplayer.data.screen.framework.json.ResponseJson;
import com.zyplayer.data.screen.repository.manage.entity.DbDatasource;
import com.zyplayer.data.screen.service.manage.DbDatasourceService;
import com.zyplayer.data.screen.service.manage.PrivateKeyService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 数据源控制器
 *
 * @author 暮光：城中城
 * @since 2019年6月29日
 */
@RestController
@RequestMapping("/datasource")
public class DbDatasourceController {
	
	@Resource
	DatabaseRegistrationBean databaseRegistrationBean;
	@Resource
	DbDatasourceService dbDatasourceService;
	@Resource
	PrivateKeyService privateKeyService;
	
	@PostMapping(value = "/list")
	public ResponseJson list() {
		privateKeyService.validateSecureParam();
		QueryWrapper<DbDatasource> wrapper = new QueryWrapper<>();
		wrapper.eq("yn", 1);
		List<DbDatasource> datasourceList = dbDatasourceService.list(wrapper);
		for (DbDatasource dbDatasource : datasourceList) {
			dbDatasource.setSourcePassword("***");
		}
		return DataResponse.ok(datasourceList);
	}
	
	@PostMapping(value = "/update")
	public ResponseJson update(DbDatasource dbDatasource) {
		privateKeyService.validateSecureParam();
		if (StringUtils.isBlank(dbDatasource.getName())) {
			return DataResponse.warn("名字必填");
		} else if (StringUtils.isBlank(dbDatasource.getDriverClassName())) {
			return DataResponse.warn("驱动类必选");
		} else if (StringUtils.isBlank(dbDatasource.getSourceType())) {
			return DataResponse.warn("数据源类型必选");
		} else if (StringUtils.isBlank(dbDatasource.getSourceUrl())) {
			return DataResponse.warn("地址必填");
		} else if (StringUtils.isBlank(dbDatasource.getSourceName())) {
			return DataResponse.warn("用户名必填");
		} else if (StringUtils.isBlank(dbDatasource.getSourcePassword())) {
			return DataResponse.warn("密码必填");
		}
		if (Objects.equals("***", dbDatasource.getSourcePassword())) {
			dbDatasource.setSourcePassword(null);
		}
		dbDatasource.setCreateTime(null);
		Long sourceId = Optional.ofNullable(dbDatasource.getId()).orElse(0L);
		if (sourceId > 0) {
			dbDatasourceService.updateById(dbDatasource);
		} else {
			dbDatasource.setCreateTime(new Date());
			dbDatasource.setYn(1);
			dbDatasourceService.save(dbDatasource);
		}
		databaseRegistrationBean.removeDatabaseFactoryBean(dbDatasource.getId());
		return DataResponse.ok();
	}
}

